<template>
  <div v-loading="tableLoading" class="vip-detail-balance-record">
    <!-- 卡片 -->
    <div class="balance-card">
      <el-row :gutter="10">
        <el-col :xs="12" :sm="12" :md="12" :lg="8">
          <div class="app-main-content-box">
            <ThreePointCard :data="cardData_1" />
          </div>
        </el-col>
        <el-col :xs="12" :sm="12" :md="12" :lg="8">
          <div class="app-main-content-box">
            <ThreePointCard :data="cardData_2" />
          </div>
        </el-col>
        <el-col :xs="12" :sm="12" :md="12" :lg="8">
          <div class="app-main-content-box">
            <ThreePointCard :data="cardData_3" />
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="app-main-content-box">
      <!-- 筛选 -->
      <div class="filter">
        <!-- 筛选 -->
        <div class="app-main-filter-collapse-box filter">
          <el-collapse>
            <el-collapse-item ref="filterCollapse" title="按条件筛选" name="1">
              <el-form
                ref="filterForm"
                :model="filterForm"
                label-width="100px"
                size="small"
              >
                <el-form-item label="选择时间：" prop="date">
                  <!-- :rules="[
                  { required: true, message: '时间区间不能为空'}
                  ]"-->
                  <el-date-picker
                    v-model="filterForm.date"
                    type="datetimerange"
                    range-separator="~"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    :default-time="['00:00:00', '23:59:59']"
                  />
                </el-form-item>
                <el-form-item label="业务单号：" prop="bizOrderNo">
                  <el-input
                    v-model="filterForm.bizOrderNo"
                    placeholder="请输入业务单号"
                    style="width: 400px"
                  />
                </el-form-item>
                <el-form-item label="商户：" prop="pubDomainBusinessId">
                  <el-select
                    v-model="filterForm.pubDomainBusinessId"
                    filterable
                    placeholder="可通过名称搜索"
                    style="width: 400px"
                  >
                    <el-option
                      v-for="(item, index) in shopList"
                      :key="index"
                      :label="item.businessName"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="变动类型：" prop="recordTypes">
                  <el-checkbox
                    v-model="checkAllRecordTypes"
                    :indeterminate="isIndeterminateRecordTypes"
                    class="fl check-all"
                    @change="handlecheckAllRecordTypesChange"
                    >全选</el-checkbox
                  >
                  <el-checkbox-group
                    v-model="filterForm.recordTypes"
                    @change="handleCheckRecordTypesChange"
                  >
                    <el-checkbox
                      v-for="(item, index) in recordTypesCheckOptions"
                      :key="index"
                      :label="item.value"
                      >{{ item.label }}</el-checkbox
                    >
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item class="filter-btn">
                  <el-button
                    type="primary"
                    round
                    @click="submitForm('filterForm')"
                    >查 询</el-button
                  >
                  <el-button round @click="resetForm('filterForm')"
                    >重 置</el-button
                  >
                </el-form-item>
              </el-form>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>

      <!-- 列表 -->
      <div class="balance-table">
        <el-table
          size="small"
          :data="list"
          stripe
          border
          style="width: 100%"
          empty-text="暂无数据"
        >
          <el-table-column
            prop="createTime"
            label="变动时间"
            fixed="left"
            width="150"
          />
          <el-table-column
            prop="bizOrderNo"
            label="业务单号"
            fixed="left"
            width="150"
          >
            <template slot-scope="scope">
              {{ scope.row.bizOrderNo || "无" }}
            </template>
          </el-table-column>
          <el-table-column prop="recordType" label="变动类型">
            <template slot-scope="scope">
              {{ recordOptions[scope.row.recordType] || "无" }}
            </template>
          </el-table-column>
          <el-table-column prop="payment" label="支付方式">
            <template slot-scope="scope">
              {{ paymentOptions[scope.row.payment] || "无" }}
            </template>
          </el-table-column>
          <el-table-column prop="balance" label="变动金额(元)">
            <template slot-scope="scope">
              <div v-if="Number(scope.row.balanceFee) == 0">
                {{ Number(scope.row.balanceFee) }}
              </div>
              <div
                v-else
                :class="
                  scope.row.balanceFee > 0
                    ? 'app-text-color-danger'
                    : 'app-text-color-success'
                "
              >
                {{
                  scope.row.balanceFee > 0
                    ? "+" + (scope.row.balanceFee / 100).toFixed(2)
                    : (scope.row.balanceFee / 100).toFixed(2)
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="balance" label="变动后总余额(元)">
            <template slot-scope="scope">
              {{ (scope.row.balance / 100).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="shopName" label="商户">
            <template slot-scope="scope">
              <span>{{
                scope.row.businessName ? scope.row.businessName : "无"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="业务备注" />
        </el-table>
        <!-- 分页 -->
        <pagination-direction
          v-if="paginationConfig.total !== 0"
          :config="paginationConfig"
          @sizeschange="sizesChange"
          @pagechange="pageChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  balanceStatistics,
  getBalanceRecord,
  pubDomainBusinessList,
} from "@/publicApi/publicDomain";

// 组件
import ThreePointCard from "@/views/vip/detail/components/ThreePointCard/index.vue";
export default {
  components: {
    ThreePointCard,
  },
  props: {
    activeName: {
      type: String,
      require: true,
    },
    vipDetail: {
      type: Object,
      require: true,
    },
  },
  data() {
    return {
      // 配置
      paginationConfig: {
        // 分页配置
        direction: "center", // 分页位置
        layout: "total, sizes, prev, pager, next, jumper", // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10, // 每页条数-默认10
      },
      recordTypesCheckOptions: [
        {
          label: "充值",
          value: 1,
        },
        {
          label: "赠送",
          value: 2,
        },
        {
          label: "消费",
          value: 3,
        },
        {
          label: "退款",
          value: 4,
        },
        {
          label: "扣除",
          value: 5,
        },
        {
          label: "人工客服",
          value: 6,
        },
      ],
      recordOptions: {
        1: "充值",
        2: "赠送",
        3: "消费",
        4: "退款",
        5: "扣除",
        6: "人工客服",
        7: "人工客服",
      },
      paymentOptions: {
        1: "微信",
        2: "余额",
        3: "支付宝",
        4: "银联",
        5: "现金",
        6: "花呗",
        7: "云闪付",
      },
      recordTypesOptions: [1, 2, 3, 4, 5, 6],
      // 状态
      tableLoading: false, // 表格loading
      checkAllRecordTypes: true, // recordType 多选状态
      isIndeterminateRecordTypes: false, // recordType
      // 数据
      cardData_1: ["总余额", 0, "累计获得", 0, "累计消费", 0],
      cardData_2: ["实充余额", 0, "累计充值", 0, "累计消费", 0],
      cardData_3: ["赠送余额", 0, "累计赠送", 0, "累计消费", 0],
      filterForm: {
        date: [],
        shopId: "",
        recordTypes: [1, 2, 3, 4, 5, 6],
        bizOrderNo: "",
        deviceId: "",
        bizCode: "all",
        sourceCode: "all",
        payment: "all",
        pubDomainBusinessId: "",
        pubDomainCustomerId: "",
      },
      list: [], // 表格数据
      shopList: [],
    };
  },
  computed: {
    ...mapGetters([
      "manageBizCodeOptions",
      "sourceCodeOptions",
      "paymentOptions",
    ]),
    shopId() {
      return this.filterForm.shopId;
    },
  },
  watch: {
    activeName(val) {
      if (val === "balance") {
        this.fetchData();
        pubDomainBusinessList({ page: 1, pageSize: 999 }).then((res) => {
          if (res.code == 0) {
            this.shopList = res.data.list;
          }
        });
      } else {
        this.resetForm("filterForm");
      }
    },
    shopId(newValue, oldValue) {
      this.filterForm.deviceId = "";
    },
  },
  mounted() {},
  methods: {
    /**
     *  获取数据
     */
    // 获取数据
    fetchData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      this.$refs.filterForm.validate(async (valid) => {
        if (valid) {
          // 请求数据
          const params = await this.setRequestParams();
          params.pageNum = page;
          params.pageSize = pageSize;
          const statisticParams = {};
          statisticParams.pubDomainCustomerId = params.pubDomainCustomerId;
          this.tableLoading = true;
          Promise.all([
            this.getTotal(statisticParams),
            this.getRecord(params),
          ]).then(() => {
            this.tableLoading = false;
          });
        }
      });
    },

    // 获取请求筛选数据
    setRequestParams() {
      return new Promise((resolve, reject) => {
        const params = Object.assign({}, this.filterForm);
        params.startTime = params.date ? params.date[0] : "";
        params.endTime = params.date ? params.date[1] : "";
        delete params.date;
        params.pubDomainCustomerId = this.vipDetail.customerId;
        if(params.recordTypes.indexOf(7)!==-1){
          params.recordTypes.splice(params.recordTypes.indexOf(7), 1);
        }
        if (params.recordTypes.indexOf(6) != -1) {
          params.recordTypes.push(7);
        }
       
        console.log(params.recordTypes)
        // params.pubDomainCustomerId = 304;
        // 清除多余字段
        for (const key in params) {
          if (params[key] === "" || params[key] === "all") {
            delete params[key];
          }
        }
        resolve(params);
      });
    },

    // 获取统计
    getTotal(statisticParams) {
      console.log(statisticParams);
      return new Promise((resolve, reject) => {
        balanceStatistics(statisticParams)
          .then((res) => {
            this.setCardTotal(res.data);
          })
          .catch((err) => {})
          .finally(() => {
            resolve();
          });
      });
    },

    // 获取记录
    getRecord(params) {
      if (params.bizOrderNo) {
        delete params.beginTimestamp;
        delete params.endTimestamp;
      }
      return new Promise((resolve, reject) => {
        getBalanceRecord(params)
          .then((res) => {
            this.list = res.data.list;
            this.paginationConfig.total = res.data.total;
            this.paginationConfig.page = res.data.pageNum;
          })
          .catch((err) => {})
          .finally(() => {
            resolve();
          });
      });
    },

    setCardTotal(data) {
      // 赋值卡片一  总
      this.cardData_1.splice(
        1,
        1,
        this.$options.filters.parseNumberToThousands(data.balance)
      ); // 余额
      this.cardData_1.splice(
        3,
        1,
        this.$options.filters.parseNumberToThousands(data.balanceSum)
      ); // 累计获得
      this.cardData_1.splice(
        5,
        1,
        this.$options.filters.parseNumberToThousands(data.balanceSumConsume)
      ); // 累计消费
      // 赋值卡片二 实充
      this.cardData_2.splice(
        1,
        1,
        this.$options.filters.parseNumberToThousands(data.realAccount)
      ); // 实充余额
      this.cardData_2.splice(
        3,
        1,
        this.$options.filters.parseNumberToThousands(data.realSumRecharge)
      ); // 累计充值
      this.cardData_2.splice(
        5,
        1,
        this.$options.filters.parseNumberToThousands(data.realSumConsume)
      ); // 累计消费
      // 赋值卡片三 赠送
      this.cardData_3.splice(
        1,
        1,
        this.$options.filters.parseNumberToThousands(data.giveAccount)
      ); // 赠送余额
      this.cardData_3.splice(
        3,
        1,
        this.$options.filters.parseNumberToThousands(data.giveSumRecharge)
      ); // 累计赠送
      this.cardData_3.splice(
        5,
        1,
        this.$options.filters.parseNumberToThousands(data.giveSumConsume)
      ); // 累计消费
    },

    // 分页sizes改变
    sizesChange() {
      this.fetchData();
    },

    // 分页page改变
    pageChange() {
      this.fetchData();
    },

    /**
     * 按钮
     */
    // 查询
    submitForm() {
      this.fetchData(1);
    },

    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.checkAllRecordTypes = true; // recordType 多选状态
      this.isIndeterminateRecordTypes = false; // recordType
      this.fetchData()
    },

    /**
     * 状态
     */
    // checkAllRecordType多选状态
    handlecheckAllRecordTypesChange(val) {
      if (val) {
        this.filterForm.recordTypes = this.recordTypesOptions;
        this.checkAllRecordTypes = true;
      } else {
        this.filterForm.recordTypes = [];
        this.checkAllRecordTypes = false;
      }
      this.isIndeterminateRecordTypes = false;
    },

    handleCheckRecordTypesChange(value) {
      const checkedLength = value.length;
      const maxLength = this.recordTypesOptions.length;
      this.checkAllRecordTypes = checkedLength === maxLength;
      this.isIndeterminateRecordTypes =
        checkedLength > 0 && checkedLength < maxLength;
    },
  },
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.vip-detail-balance-record {
  /* 卡片 */
  .balance-card {
    .app-main-content-box {
      margin-bottom: 10px;
    }
  }
  /* 重置多选左边距 */
  .el-checkbox + .el-checkbox {
    margin-left: 0;
  }
  .el-checkbox {
    margin-right: 10px;
  }
}

/* 筛选 */
.filter {
  .filter-btn {
    margin-bottom: 20px;
  }
  .check-all {
    margin-right: 30px;
  }
  .el-select {
    width: 120px;
  }
  .input-with-select {
    width: 400px;
  }
  // 换行
  .el-radio + .el-radio {
    margin-left: 0;
  }
  .el-radio {
    margin-right: 10px;
    height: 32px;
    line-height: 32px;
  }
}
</style>
